//
//  VisitingFamilyViewController.m
//  CarLife
//
//  Created by yu on 2018/1/29.
//  Copyright © 2018年 jpas. All rights reserved.
//

#import "VisitingFamilyViewController.h"

#import "VisitingFamilyCell.h"
#import "QuestionModel.h"
#import "VisitingImageModel.h"
#import "XLPhotoBrowser.h"
#import "VisitingInfoModel.h"
#import "SignatureView.h"
#import "Utility.h"
#import "SignatureViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface VisitingFamilyViewController ()<UITableViewDataSource,UITableViewDelegate
,UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *questions;

@property (nonatomic, strong) NSMutableArray *photoDes;

@property (nonatomic, strong) NSMutableArray *images;

@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, strong) NSMutableArray *signArray;

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) VisitingInfoModel *viModel;

@property (nonatomic, assign) BOOL isVisitFamily;

@property (nonatomic, strong) KLCPopup *popup;

@property (nonatomic, strong) SignatureView *signatureView;

@property (nonatomic, strong) UIButton *checkBtn;

@property (nonatomic, copy) NSString *signTime;

@end

@implementation VisitingFamilyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    PPLog(@"工单号 == %@",self.woModel.workOrderNo);
    self.navigationItem.title = [self homeVisType];
    self.viModel = [VisitingInfoModel initVisitingInfo];
    self.isVisitFamily = [self.woModel.homeVisitsType isEqualToString:@"1"];
    [self setLeftImageNamed:@"back_white" action:@selector(returnAction)];
    
    if (self.enterVisType == EnterByTakingPictures) {
        [self initQuestionData];
        [self initImageData];
        [self setupPopupView];
    }
}

- (void)returnAction
{
    if (self.enterVisType == EnterByWorkorderDetail) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前工单未完成，如果退出所有已填信息将失效,是否确定退出？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)setupPopupView
{
    if (self.popup == nil) {
        self.signatureView = [[SignatureView alloc] init];
        self.signatureView.backgroundColor = [UIColor whiteColor];
        self.signatureView.size_sd = CGSizeMake(kScreenWidth, kAutoHeight(300));
        
        self.popup = [KLCPopup popupWithContentView:self.signatureView
                                           showType:KLCPopupShowTypeSlideInFromBottom
                                        dismissType:KLCPopupDismissTypeSlideOutToBottom
                                           maskType:KLCPopupMaskTypeDimmed
                           dismissOnBackgroundTouch:NO
                              dismissOnContentTouch:NO];
        
  /*
#pragma mark - cancel
        @weakify(self);
        [self.signatureView setCancelBlock:^{
            @strongify(self);
            if (self.signArray.count) {
                self.checkBtn.selected = YES;
            } else {
                self.checkBtn.selected = NO;
            }
            PPLog(@"sign count == %ld",self.signArray.count);
            [self.popup dismiss:YES];
        }];
#pragma mark - resign
        [self.signatureView setResignBlock:^{
            @strongify(self);
            [self.signatureView.signView clearSignature];
        }];
#pragma mark - conform
        [self.signatureView setConfirmBlock:^{
            @strongify(self);
            UIImage *image = [self.signatureView.signView getSignatureImage];
            PPLog(@"777==%lf",image.size.height);
            if (image) {
                self.signArray = [NSMutableArray array];
                [self.signArray addObject:image];
                self.checkBtn.selected = YES;
                self.signTime = [Utility dateToStringFromFormat:@"yyyy-MM-dd HH:mm:ss" withDate:[NSDate date]];
                [self.popup dismiss:YES];
            }
            PPLog(@"sign image count == %ld",[self.signArray count]);
        }];
   */
    }
}

//未接单：2  已接单：4  完成工单：3
- (void)initImageData
{
    NSArray *images;
    if (self.isVisitFamily) {
       images = @[@{@"title":@"客户所住小区门口带有小区名称标识的；",@"image":@"",},@{@"title":@"客户家门口带有门牌号的；",@"image":@"",},@{@"title":@"客户客厅全貌的（含地板、沙发、顶灯等）；",@"image":@""},@{@"title":@"其他认为具有意义的（例如：书房、含影视墙、含博古架的位置）",@"image":@"",}];
    } else {
        images = @[@{@"title":@"含有公司招牌的外景（门头房的尽量取含周边的全景，写字楼的尽量取前台LOGO墙）",@"image":@"",},@{@"title":@"公司办公场所内景（包含：员工、工位、办公设备、机器设备、库存产品等）",@"image":@"",},@{@"title":@"跟客户在其办公场所内的合影",@"image":@""},@{@"title":@"其他认为具有意义的（例如：悬挂在墙上的营业执照、许可证、荣誉证书等）",@"image":@"",}];
    }
    
    self.images = [NSMutableArray array];
    for (NSDictionary *dict in images) {
        VisitingImageModel *imageModel = [[VisitingImageModel alloc] init];
        imageModel.title = dict[@"title"];
        imageModel.image = nil;
        [self.images addObject:imageModel];
    }
}

- (void)initQuestionData
{
    self.questions = [NSMutableArray array];
    [self.requestTool loadVisitingQuestionByVisId:@"1" visType:self.woModel.homeVisitsType success:^(NSMutableArray *questionList) {
        self.questions = questionList;
        [self.tableView reloadData];
    } failure:^(NSString *error) {
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.enterVisType == EnterByWorkorderDetail) {
        return 1;
    } else {
       return 4;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.enterVisType == EnterByWorkorderDetail) {
        return 1;
    } else {
        if (section == 2) {
            return self.questions.count;
        } else if (section == 3) {
            return self.images.count;
        } else {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VisitingFamilyCell *vfCell = [VisitingFamilyCell initTableViewCellWith:tableView indexPath:indexPath];
    
    if (indexPath.section == 0) {
        vfCell.woModel = self.woModel;
    } else if (indexPath.section == 1) {
        vfCell.viModel = self.viModel;
    } else if (indexPath.section == 2) {
        vfCell.questionModel = self.questions[indexPath.row];
        vfCell.tableView = tableView;
        vfCell.answerYBtn.tag = indexPath.row+1;
        vfCell.answerNBtn.tag = indexPath.row+1;
    } else if (indexPath.section == 3) {
        VisitingImageModel *imageModel = self.images[indexPath.row];
        vfCell.imageModel = imageModel;
        vfCell.photoBtn.tag = indexPath.row+1;
        vfCell.imgView.tag = indexPath.row+1;
        vfCell.tableView = tableView;
    }

#pragma mark - Block -
    @weakify(self);
    [vfCell setPhotoActionBlock:^(NSInteger index,UIImagePickerController *imagePicker) {
        @strongify(self);
        
        // 1、 获取摄像设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (device) {
            AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (status == AVAuthorizationStatusNotDetermined) {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        // 用户第一次同意了访问相机权限
                        PPLog(@"用户第一次同意了访问相机权限111");
                        [self presentViewController:imagePicker animated:YES completion:nil];
                    } else {
                        // 用户第一次拒绝了访问相机权限
                        PPLog(@"用户第一次拒绝了访问相机权限666");
                    }
                }];
            } else if (status == AVAuthorizationStatusAuthorized) { //用户允许当前应用访问相机
                PPLog(@"允许访问相机");
                [self presentViewController:imagePicker animated:YES completion:nil];
            } else if (status == AVAuthorizationStatusDenied) { //用户拒绝当前应用访问相机
                PPLog(@"拒绝访问相机");
                [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启相机服务(设置>隐私>相机>开启)，进行拍照上传" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
            } else if (status == AVAuthorizationStatusRestricted) {
                PPLog(@"因为系统原因, 无法访问相册");
            }
        } else {
            PPLog(@"未检测到摄像头(模拟器等)");
        }
    }];
    
    [vfCell setPickerBlock:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    // 图片点击
    [vfCell setTapImageBlock:^(NSInteger index) {
        @strongify(self);
        [self.imageArray removeAllObjects];
        for (VisitingImageModel *imageModel in self.images) {
            if (imageModel.image != nil) {
                [self.imageArray addObject:imageModel.image];
            }
        }
        PPLog(@"图片个数==%ld",self.imageArray.count);
        [XLPhotoBrowser showPhotoBrowserWithImages:self.imageArray currentImageIndex:index];
    }];
    
    return vfCell;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 3?130:0.001;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor lightGrayColor];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        UIView *bgView = [[UIView alloc] init];
        
        //复选框
        UIButton *checkBtn = [[UIButton alloc] init];
        self.checkBtn = checkBtn;
        if (self.signArray.count) {
            checkBtn.selected = YES;
        }
        [checkBtn setImage:IMAGE_NAMED(@"q_check_nor") forState:UIControlStateNormal];
        [checkBtn setImage:IMAGE_NAMED(@"q_check_sel") forState:UIControlStateSelected];
        [checkBtn addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:checkBtn];
        
        NSMutableAttributedString *protocol = [[NSMutableAttributedString alloc] initWithString:@"本人承诺已阅读并同意《家访调查制度》" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor darkTextColor]}];
        [protocol addAttribute:NSLinkAttributeName value:@"click://" range:NSMakeRange(10, 8)];
        [protocol addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.5],NSForegroundColorAttributeName:[UIColor blueColor]} range:NSMakeRange(10, 8)];
        
        UITextView *textView = [[UITextView alloc] init];
        textView.backgroundColor = [UIColor clearColor];
        textView.delegate = self;
        textView.editable = NO;
        textView.scrollEnabled = NO;
        textView.attributedText = protocol;
        [bgView addSubview:textView];
        
        UIButton *submitBtn = [[UIButton alloc] init];
        [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
        [submitBtn setBackgroundColor:kBaseColor];
        [submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:submitBtn];
        
        checkBtn.sd_layout
        .leftSpaceToView(bgView, 10)
        .topSpaceToView(bgView, 8)
        .heightIs(30)
        .widthEqualToHeight();
        
        textView.sd_layout
        .centerYEqualToView(checkBtn)
        .leftSpaceToView(checkBtn, -5)
        .rightSpaceToView(bgView, 0)
        .heightIs(35);
        
        submitBtn.sd_layout
        .leftSpaceToView(bgView, 15)
        .topSpaceToView(textView, 20)
        .rightSpaceToView(bgView, 15)
        .heightIs(45);
        submitBtn.sd_cornerRadius = @(2);
        
        return bgView;
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!section) {
        return @"客户基本信息";
    } else if (section == 1) {
        return @"家访人员信息";
    } else if (section == 2) {
        return @"信息登记";
    } else {
        return @"照片采集";
    }
}

#pragma mark - check action
- (void)checkAction:(UIButton *)btn
{
    SignatureViewController *signatureVc = [[SignatureViewController alloc] init];
    @weakify(self);
    // 确定
    [signatureVc setConfirmBlock:^(UIImage *image) {
        @strongify(self);
        if (image) {
            PPLog(@"height = %lf",image.size.height);
            self.signArray = [NSMutableArray array];
            [self.signArray addObject:image];
            self.checkBtn.selected = YES;
            self.signTime = [Utility dateToStringFromFormat:@"yyyy-MM-dd HH:mm:ss" withDate:[NSDate date]];
        }
    }];
    // 取消
    [signatureVc setCancelBlock:^{
        @strongify(self);
        if (self.signArray.count) {
            self.checkBtn.selected = YES;
        } else {
            self.checkBtn.selected = NO;
        }
    }];
    [self presentViewController:signatureVc animated:YES completion:nil];
}

#pragma mark - submit action
- (void)submitAction
{
    [self.imageArray removeAllObjects];
    for (VisitingImageModel *imageModel in self.images) {
        if (imageModel.image != nil) {
            [self.imageArray addObject:imageModel.image];
        }
    }

    if (self.imageArray.count != 4) {
        [MBProgressHUD showToast:@"照片采集未拍全"];
        return;
    }

    if (!self.signArray.count) {
        [MBProgressHUD showToast:@"请完成电子签名"];
        return;
    }
    UIImage *signImage = [self.signArray firstObject];
//        [self.imageArray insertObject:signImage atIndex:self.imageArray.count-1];
    [self.imageArray addObject:signImage];
    
#pragma mark - SubmitWorkorder
    NSInteger i = 1;
    NSMutableArray *woReply = [NSMutableArray array];
    for (QuestionModel *questionModel in self.questions) {
        //问题原因未填写
        NSString *answerDes = questionModel.answerDes;
        if (answerDes.length > 0) {
            NSArray *components = [answerDes componentsSeparatedByString:@":"];
            if (![components.lastObject length]) {
                [[[UIAlertView alloc] initWithTitle:@"请填写题目完整答案" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                return;
            }
        }

        //答题数目不全
        NSString *answer = questionModel.answer;
        if (![answer length]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"题目未答完" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
//        PPLog(@"答案：%@**%@",questionModel.answer,questionModel.answerDes);
        ReplyModel *replyModel = [[ReplyModel alloc] init];
        replyModel.woId = self.woModel.woId;
        replyModel.wovisQuestionid = NSStringFormat(@"%ld",i++);
        replyModel.answer = questionModel.answer;
        replyModel.answerDes = questionModel.answerDes;
        replyModel.createTime = @"2018-01-01 01:01:01";
        [woReply addObject:replyModel.mj_keyValues];
    }
    //192.168.1.107
    WorkorderModel *woModel = [[WorkorderModel alloc] init];
    woModel.woId = self.woModel.woId;//工单Id
    woModel.visitTime = self.viModel.visitTime;//拜访时间
    woModel.visitorName = self.viModel.visitorName;//拜访人员名字
    woModel.visitorContract = self.viModel.visitorMobile;//拜访人员电话
    woModel.status = @"3";
    woModel.homeVisitsType = self.woModel.homeVisitsType;
    woModel.signTime = self.signTime;
    woModel.woReply = woReply;
    
    PPLog(@"visitorName == %@",woModel.woId);
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:woModel.mj_keyValues options:0 error:nil];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    PPLog(@"str == %@",str);
    
    for (UIImage *image in self.imageArray) {
        PPLog(@"%lf",image.size.height);
    }
    
    //////////// 上传提交 ///////////////
    [self.requestTool uploadWoVisImgByWoId:self.woModel.woId images:self.imageArray success:^(int status) {
        if (status == 0) {
            //家访工单提交题目
            [self.requestTool workorderUpdateVisStatus:str success:^(BOOL isFinish) {
                if (isFinish) {
                    [MBProgressHUD showToast:@"提交成功"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kReloadWorkOrderListNotification" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSString *error) {
                PPLog(@"update vis status error = %@",error);
            }];
        }
    } failure:^(NSString *error) {
        PPLog(@"upload vis img error = %@",error);
    }];
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"click"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本司声明严格遵守了贵司的家访调查制度，派遣本司调查员对上述客户进行了家访调查。调查中，本司调查员对客户进行了当面访谈并核实了相关证件及资料的原件。本司确保上表所述的信息均真实有效。若有虚假信息，本司承诺对该客户对贵司的债务（指贵司对客户提供融资租赁服务或贷款担保服务而产生的债务。）承担连带责任。" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return NO;
    }
    return YES;
}

- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (NSString *)homeVisType {
    NSString *homeVisitsType = NSStringFormat(@"%@",self.woModel.homeVisitsType);
    if ([homeVisitsType isEqualToString:@"1"]) {
        homeVisitsType = @"家庭拜访";
    } else if ([homeVisitsType isEqualToString:@"2"]) {
        homeVisitsType = @"员工公司拜访";
    } else {
        homeVisitsType = @"私营业主公司拜访";
    }
    return homeVisitsType;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
